package render;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class RenderBuffer extends JPanel
{
    
    private int numPixelsX;
    private int numPixelsY;
    
    private BufferedImage pixelBuffer;
    
    private AffineTransform matrixScale;
    
    public RenderBuffer(
            int windowWidth, 
            int windowHeight, 
            int pixelsWide, 
            int pixelsTall)
    {
        // Init buffer dimensions
        this.numPixelsX = pixelsWide;
        this.numPixelsY = pixelsTall;
        
        // Init PixelBuffer
        this.pixelBuffer = new BufferedImage(
            pixelsWide, 
            pixelsTall, 
            BufferedImage.TYPE_INT_RGB
        );
        
        // Init Scaling matrix for non-standard resolutions
        this.matrixScale = AffineTransform.getScaleInstance(
            ((double) windowWidth) / pixelsWide, 
            ((double) windowHeight) / pixelsTall
        );
        
        // Init JPanel states
        this.setSize(
            windowWidth+6, 
            windowHeight+6
        );
        this.setIgnoreRepaint(true);
        this.setFocusable(true);
    }
    
    public Graphics2D prepareGraphics()
    {
        Graphics2D g = this.pixelBuffer.createGraphics();
        
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, this.numPixelsX, this.numPixelsY);
        
        return g;
    }
    
    public void endGraphics(Graphics2D g)
    {
        g.dispose();
    }
    
    public void flip()
    {
        Graphics2D g = (Graphics2D) this.getGraphics();
        g.drawImage(
            this.pixelBuffer, // BufferedImage
            this.matrixScale, // AffineTransform for scaling
            null // ImageObserver
        );
        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }
    
}
